package edu.scau.cxq.gp.controller;


import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import edu.scau.cxq.gp.common.annotation.ResponseResult;
import edu.scau.cxq.gp.common.result.MyResult;
import edu.scau.cxq.gp.common.utils.MD5Utils;
import edu.scau.cxq.gp.common.utils.WrapperUtils;
import edu.scau.cxq.gp.dto.LoginDTO;
import edu.scau.cxq.gp.dto.UserDTO;
import edu.scau.cxq.gp.entity.User;
import edu.scau.cxq.gp.service.IUserService;
import edu.scau.cxq.gp.shiro.utils.JwtUtil;
import edu.scau.cxq.gp.vo.RecordInVO;
import edu.scau.cxq.gp.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 存储用户信息 前端控制器
 * </p>
 *
 * @author CXQ
 * @since 2022-01-28
 */
@RestController
@ResponseResult
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;

//    /**
//     * shiro
//     * @param loginDTO
//     * @param model
//     * @return
//     */
//    @PostMapping("/login")
//    public Object login(@RequestBody LoginDTO loginDTO, Model model){
//
//
//        String username = loginDTO.getUsername();
//        String password = loginDTO.getPassword();
//
//        log.info("username:{},password:{}", username, password);
//        Map<String, Object> map = new HashMap<>();
////        if (!"tom".equals(username) || !"123".equals(password)) {
////            map.put("msg", "用户名密码错误");
////            return map;
////        }
//
//        UserVO userVO = userService.getUser(username, password);
//
//        if (userVO == null) {
//            return MyResult.fail(401, "账号或密码错误");
//        }
//
//        JwtUtil jwtUtil = new JwtUtil();
//        Map<String, Object> chaim = new HashMap<>();
//        chaim.put("username", username);
//        String jwtToken = jwtUtil.encode(username, 24 * 60 * 60 * 1000, chaim); // token有效期： 一天
//        map.put("userInfo", userVO);
//        map.put("token", jwtToken);
//        return map;
//    }

    /**
     * sa-token
     * @param loginDTO
     * @param model
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestBody LoginDTO loginDTO, Model model, HttpServletRequest httpServletRequest){


        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        Map<String, Object> loginInfo = new HashMap<>();
//        if (!"tom".equals(username) || !"123".equals(password)) {
//            map.put("msg", "用户名密码错误");
//            return map;
//        }

        UserVO userVO = userService.getUser(username, password);

        if (userVO == null) {
            return MyResult.fail(401, "账号或密码错误");
        }

        if (userVO.getUserHidden() == 1) {
            return MyResult.fail(411, "该账号已被冻结");
        }

        String user = (userVO.getUserType() == 0 ? "SuperAdmin[" : "WarehouseAdmin[") + userVO.getUserAccount() + "]";
        System.out.println(user);
        StpUtil.login(user);
        String token = StpUtil.getTokenValueByLoginId(user);

        loginInfo.put("token", token);
        loginInfo.put("userInfo", userVO);

        return loginInfo;
    }

    /**
     * 注册用户
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public boolean register(@RequestBody UserDTO userDTO) {
        return userService.registerUser(userDTO);
    }

    /**
     * 检查密码
     * @param user
     * @return
     */
    @PostMapping("/logCheckPassword")
    public UserVO checkPassword(@RequestBody User user) {

        User userInfo = userService.checkUser(user);

        if (userInfo == null) {
            return null;
        }
        UserVO userVO = new UserVO();

        BeanUtils.copyProperties(userInfo, userVO);

        return userVO;
    }

    @GetMapping("/logGetUserInfo")
    public UserVO getUserInfo(@Param("userId") String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        return userVO;
    }

    /**
     * 修改用户信息
     * @return
     */
    @PostMapping("/logUpdateOne")
    public UserVO updateOne(@RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        String salt = RandomStringUtils.randomAlphabetic(4);

        String password = MD5Utils.MD5Upper(user.getUserPasswd(), salt);

        user.setUserPasswd(password);
        user.setSalt(salt);
        user.setUserHidden(0);

//        return false;

        if(userService.updateById(user)) {
            UserVO vo = new UserVO();
            BeanUtils.copyProperties(user, vo);

            return vo;
        }

        return null;
    }

//    /**
//     * shiro
//     * @return
//     */
//    @PostMapping("/logout")
//    public Map<String, Object> logout() {
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
//        Map<String, Object> resultMap = new HashMap<>();
//        resultMap.put("msg", "成功退出");
////        resultMap.put("principal", JSON.toJSON(principal));
//        return resultMap;
//    }

    /**
     * sa-token
     * @return
     */
    @PostMapping("/logout")
    public Map<String, Object> logout(@RequestBody Map<String, Object> tokenMap, HttpServletRequest httpServletRequest) {

        StpUtil.logoutByTokenValue((String) tokenMap.get("token"));
//        String loginId = (String) StpUtil.getLoginIdByToken((String) tokenMap.get("token"));
//        System.out.println(loginId);
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("msg", "成功退出");
        return resultMap;
    }

    /**
     * 分页查找用户
     * @return
     */
    @GetMapping("/selectByPage")
    public PageInfo<UserVO> selectByPage (Integer currentPage, Integer size, UserVO userVO) {
        PageInfo<UserVO> userVOList = userService.getUserVOList(currentPage, size,userVO);
        return userVOList;
    }

    /**
     * 删除（实际上是冻结）
     * @param user
     * @return
     */
    @PostMapping("/deleteOne")
    public boolean deleteOne(@RequestBody User user) {

        User find = userService.getById(user.getUserId());
        // 将隐藏位置1
        find.setUserHidden(1);
        return userService.updateById(find);
    }

    /**
     * 回复（实际上是解锁）
     * @param user
     * @return
     */
    @PostMapping("/resumeOne")
    public boolean resumeOne(@RequestBody User user) {
        QueryWrapper queryWrapper = WrapperUtils.entitytoWrapper(user);
        user = userService.getOne(queryWrapper);
        // 将隐藏位置1
        user.setUserHidden(0);
        return userService.updateById(user);
    }
}
